"""
转换文件编码为UTF-8
"""

import cchardet


def convert_to_utf8(input_file, output_file=None):
    # 如果未指定输出文件，默认在原文件名后加"_utf8"
    if output_file is None:
        import os

        name, ext = os.path.splitext(input_file)
        output_file = f"{name}_utf8{ext}"

    try:
        # 以二进制模式读取文件
        with open(input_file, "rb") as f:
            content = f.read()

        # 检测文件编码
        result = cchardet.detect(content)
        encoding = result["encoding"]
        confidence = result["confidence"]

        print(f"检测到的编码: {encoding} (可信度: {confidence:.2f})")

        if not encoding:
            print("无法确定文件编码，尝试使用默认编码")
            encoding = "gbk"  # 中文文件常见编码

        # 用检测到的编码读取内容
        text = content.decode(encoding, errors="replace")  # 遇到错误时替换为�

        # 以UTF-8编码保存
        with open(output_file, "w", encoding="utf-8") as f:
            f.write(text)

        print(f"文件已成功转换为UTF-8编码并保存至: {output_file}")
        return True

    except Exception as e:
        print(f"转换失败: {str(e)}")
        return False


# 使用示例
if __name__ == "__main__":
    input_filename = "《剑来》作者：烽火戏诸侯.txt"
    convert_to_utf8(input_filename)
